# -*- coding: utf-8 -*-
# author:HHR
# time:2021/1/14:18:10
# ___msg___ = '抓取企业专利信息'
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from quote_folder.Db_connect import DB_connect
from selenium.webdriver.common.by import By
from selenium import webdriver
from bs4 import BeautifulSoup
import time, random, re



class Enterprisepaten():
	def __init__(self):
		self.get_url = "http://cpquery.cnipa.gov.cn/"
		self.bigdata_con = DB_connect().online_big_data()  # 数据组数据库连接
		self.bigdata_cur = self.bigdata_con.cursor()

	def login_gov_xhhg(self):
		""" 登录中国及多国(信合红谷) """
		profile = webdriver.FirefoxOptions()
		profile.set_preference('network.proxy.type', 1)
		browser = webdriver.Firefox(options=profile, executable_path=r'/Users/mac/Downloads/geckodriver')
		browser.get(self.get_url)
		time.sleep(5)
		WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, "username"))).clear()
		# browser.find_element_by_id('username').clear()
		browser.find_element_by_id('username').send_keys('42264')
		time.sleep(1)
		browser.find_element_by_id('password').clear()
		browser.find_element_by_id('password').send_keys('Xhhg0613@@')
		time.sleep(random.randint(30, 50))
		current_url = browser.current_url
		return browser, current_url

	def login_gov_xh(self):
		""" 登录中国及多国(协和) """
		profile = webdriver.FirefoxOptions()
		profile.set_preference('network.proxy.type', 1)
		browser = webdriver.Firefox(options=profile, executable_path=r'/Users/mac/Downloads/geckodriver')
		browser.get(self.get_url)
		time.sleep(5)
		WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, "username"))).clear()
		# browser.find_element_by_id('username').clear()
		browser.find_element_by_id('username').send_keys('CN00675769')
		time.sleep(1)
		browser.find_element_by_id('password').clear()
		browser.find_element_by_id('password').send_keys('Gv89NWWY@')
		time.sleep(random.randint(30, 50))
		current_url = browser.current_url
		return browser, current_url

	def get_pantent_msg(self, soup, enterprise):
		tr_list = soup.select("div[class='content_listx2'] tr")
		flag = False
		if len(tr_list) < 200:
			flag = True
		for tr_tag in tr_list:
			td_list = tr_tag.select("td")
			applicationNumber = td_list[0].text		# 申请号
			patentName = td_list[1].text.strip()		# 专利名称
			patentee = td_list[2].select("span")[0]["title"]		# 申请人
			applyDay = td_list[3].select("span")[0]["title"]		# 申请日
			impowerDay = td_list[4].select("span")[0]["title"]		# 授权日
			patentType = td_list[5].text					# 专利类型
			caseStatus = td_list[7].select("span")[0]["title"]			# 案件状态
			print(applicationNumber, " | ", patentName, " | ", patentee, " | ", applyDay, " | ", impowerDay, " | ", patentType, " | ", caseStatus)

			insert_sql = f"""INSERT INTO UnitPatentData (`applicationNumber`, `patentName`, `patentee`, `applyDay`, `impowerDay`, `patentType`, searchKey, caseStatus) VALUES ("{"ZL"+applicationNumber}", "{patentName}", "{patentee}", "{applyDay}", "{impowerDay}", "{patentType}", "{enterprise}", "{caseStatus}")"""
			try:
				self.bigdata_cur.execute(insert_sql)
			except Exception as E:
				updata_sql = f"""UPDATE UnitPatentData SET caseStatus='{caseStatus}' WHERE applicationNumber='{"ZL"+applicationNumber}'"""
				try:
					self.bigdata_cur.execute(updata_sql)
				except:
					print(updata_sql)
		self.bigdata_con.commit()
		return flag

	def get_msg(self, enterprise, browser):
		start_row = 1
		while True:
			url = f"http://cpquery.cnipa.gov.cn//txnQueryOrdinaryPatents.do?select-key%3Asortcol=&select-key%3Asort=&attribute-node%3Apagerow=20&attribute-node%3Astartrow=1&checkflag%3Aflag=1&select-key%3Ashenqingh=&select-key%3Azhuanlimc=&select-key%3Ashenqingrxm={enterprise}&select-key%3Azhuanlilx=&select-key%3Ashenqingr_from=&select-key%3Ashenqingr_to=&select-key%3Adailirxm=&very-code=&captchaNo=&fanyeflag=1&verycode=fanye&attribute-node:record_start-row={start_row}&attribute-node:record_page-row=200&#anchor"
			browser.get(url)
			time.sleep(10)
			count_page = browser.page_source
			soup = BeautifulSoup(count_page, "lxml")
			print('-' * 50, f"开始抓取专利信息, 从 {start_row} 条开始", '-' * 50)
			flag = self.get_pantent_msg(soup, enterprise)
			if flag:
				break
			else:
				start_row += 200

	def main_fun(self, enterprise_name):
		if enterprise_name == "华中科技大学同济医学院附属协和医院":
			browser, current_url = self.login_gov_xh()
			self.get_msg(enterprise_name, browser)
			browser.close()
			time.sleep(5)
		browser, current_url = self.login_gov_xhhg()
		self.get_msg(enterprise_name, browser)
		self.bigdata_cur.close()
		self.bigdata_con.close()
		browser.close()


if __name__ == '__main__':
	Enterprisepaten().main_fun("华中科技大学同济医学院附属协和医院")
